package com.iflytek.universitymanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iflytek.universitymanagement.domain.ScoreAnalysisResult;
import com.iflytek.universitymanagement.domain.StudentScore;
import com.iflytek.universitymanagement.mapper.StudentScoreMapper;
import com.iflytek.universitymanagement.service.StudentScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StudentScoreServiceImpl extends ServiceImpl<StudentScoreMapper, StudentScore> implements StudentScoreService {

    @Autowired
    private StudentScoreMapper studentScoreMapper;

    // 获取单个学生的平均成绩
    @Override
    public BigDecimal getAverageScoreByStudentId(Integer studentId) {
        List<StudentScore> scores = this.lambdaQuery().eq(StudentScore::getStudentId, studentId).list();
        if (scores.isEmpty()) {
            return BigDecimal.ZERO;
        }
        return scores.stream()
                .map(StudentScore::getScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .divide(BigDecimal.valueOf(scores.size()), 2, BigDecimal.ROUND_HALF_UP);
    }

    // 获取单个学生的成绩分析
    @Override
    public ScoreAnalysisResult getScoreAnalysisByStudentId(Integer studentId) {
        // 获取学生的成绩数据，并联接课程表
        List<StudentScore> scores = studentScoreMapper.getStudentScoresWithCourseName(studentId);

        BigDecimal totalScore = BigDecimal.ZERO;
        List<String> highScores = new ArrayList<>();
        List<String> lowScores = new ArrayList<>();

        // 遍历成绩并分类为高分和低分
        for (StudentScore score : scores) {
            totalScore = totalScore.add(score.getScore());

            // 获取课程名称
            String courseName = score.getCourseName();  // 通过联表查询已获得课程名称

            if (score.getScore().compareTo(BigDecimal.valueOf(85)) >= 0) {
                highScores.add(courseName);
            } else if (score.getScore().compareTo(BigDecimal.valueOf(60)) < 0) {
                lowScores.add(courseName);
            }
        }

        BigDecimal averageScore = scores.isEmpty() ? BigDecimal.ZERO : totalScore.divide(BigDecimal.valueOf(scores.size()), 2, BigDecimal.ROUND_HALF_UP);

        // 生成成绩分析
        StringBuilder analysis = new StringBuilder();
        analysis.append("学生的平均分为 ").append(averageScore).append("，");

        if (!highScores.isEmpty()) {
            analysis.append(String.join("、", highScores)).append("表现优异，");
        }
        if (!lowScores.isEmpty()) {
            analysis.append(String.join("、", lowScores)).append("需要改进。");
        }

        // 获取学生姓名
        String studentName = studentScoreMapper.getStudentNameById(studentId);

        // 构建并返回分析结果
        ScoreAnalysisResult result = new ScoreAnalysisResult();
        result.setStudentId(studentId);
        result.setStudentName(studentName);
        result.setAverageScore(averageScore);
        result.setHighScores(highScores);
        result.setLowScores(lowScores);
        result.setAnalysis(analysis.toString());

        return result;
    }

    @Override
    public Page<ScoreAnalysisResult> getAllStudentScoreAnalysis(Page<StudentScore> page) {
        // 获取分页后的学生成绩
        Page<StudentScore> scorePage = studentScoreMapper.getAllStudentScores(page);

        // 用来存储唯一的学生 ID
        Set<Integer> processedStudentIds = new HashSet<>();

        // 用来存储所有学生的成绩分析结果
        List<ScoreAnalysisResult> resultList = new ArrayList<>();

        // 遍历学生成绩记录
        for (StudentScore score : scorePage.getRecords()) {
            Integer studentId = score.getStudentId();

            // 如果该学生已经被处理过，跳过
            if (!processedStudentIds.contains(studentId)) {
                // 调用已有的分析方法来计算成绩分析
                ScoreAnalysisResult result = getScoreAnalysisByStudentId(studentId);

                // 添加到结果列表
                resultList.add(result);

                // 记录该学生 ID 已处理
                processedStudentIds.add(studentId);
            }
        }

        // 创建新的分页对象，填充分析结果
        Page<ScoreAnalysisResult> resultPage = new Page<>();
        resultPage.setRecords(resultList);  // 设置分页记录为分析结果
        resultPage.setTotal(processedStudentIds.size());  // 设置总记录数为唯一学生数
        resultPage.setCurrent(scorePage.getCurrent());  // 设置当前页
        resultPage.setSize(scorePage.getSize());  // 设置每页大小

        return resultPage;
    }



    @Override
    public IPage<StudentScore> selectPage(int pageNum, int pageSize, String name, String courseName) {
        QueryWrapper<StudentScore> queryWrapper = new QueryWrapper<>();
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("s.name", name); // Assuming 's' is the alias for the student table
        }
        if (courseName != null && !courseName.trim().isEmpty()) {
            queryWrapper.like("c.course_name", courseName); // Assuming 'c' is the alias for the course table
        }
        queryWrapper.orderByAsc("score_id");
        return studentScoreMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
    }



    @Override
    public IPage<StudentScore> getScoresWithPagination(int pageNum, int pageSize) {
        Page<StudentScore> page = new Page<>(pageNum, pageSize);
        return studentScoreMapper.getAllScoresWithDetails(page);
    }

    @Transactional
    public boolean addStudentScore(StudentScore studentScore) {
        // 插入学生成绩
        return studentScoreMapper.insert(studentScore) > 0;
    }
    @Override
    public List<StudentScore> getStudentProgressAndScoresByName(String name) {
        return studentScoreMapper.getStudentProgressAndScoresByName(name);
    }
}
